package com.atguigu.gmall.web.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * feign 请求拦截器解决远程调用丢失请求头问题
 *
 * 功能：每次远程调用时，把老请求头 继续设置到新请求头中，往下透传
 * @Author 卡尼奶
 * @Date 2022/6/1 21:02
 * @Version 1.0
 */
@Component
public class UserHeaderRequest implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {

        ServletRequestAttributes request = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String userId = request.getRequest().getHeader("UserId");
        String userTempId = request.getRequest().getHeader("UserTempId");

        if (userId != null) {
            template.header("UserId",userId);
        }
        if (userTempId != null) {
            template.header("UserTempId",userTempId);
        }
    }
}
